﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using SqlServerMaintenanceSolution.Commands;
using Microsoft.Win32;
using SqlServerMaintenanceSolution.Models;
using System.Windows.Data;
using System.Windows.Controls;
using SqlServerMaintenanceSolution.Models.Enums;


namespace SqlServerMaintenanceSolution.ViewModels
{
    public class ConnectionPropertiesViewModel : ViewModelBase, INotifyPropertyChanged
    {
        private DelegateCommand exitCommand;
        #region Sql Server Instance List
        private IList<SqlServerInstance> sqlServerInstanceList;
        private readonly CollectionView _sqlServerInstances;
        private SqlServerInstance SqlServerInstance;
        private string _sqlServerInstanceCompleteName;
        public string SqlServerInstanceCompleteName
        {
            get { return _sqlServerInstanceCompleteName; }
            set
            {
                if (_sqlServerInstanceCompleteName == value) return;
                _sqlServerInstanceCompleteName = value;

                this.SqlServerInstance = new SqlServerInstance(_sqlServerInstanceCompleteName);

                OnPropertyChanged("SqlServerInstance");
            }
        }

        public CollectionView SqlServerInstances
        {
            get { return _sqlServerInstances; }
        }
        #endregion

        #region Sql Server Authentication
        private IList<SqlServerAuthentication> sqlServerAuthenticationList;
        private readonly CollectionView _sqlServerAuthentications;
        private SqlServerAuthentication SqlServerAuthentication;
        private string _authentication;
        public bool IntegratedSecurity
        {
            get
            {
                if (SqlServerAuthentication != null)
                    return !SqlServerAuthentication.IntegratedSecurity;
                else
                    return false;
            }
        }
        public string Authentication
        {
            get { return _authentication; }
            set
            {
                if (_authentication == value) return;
                _authentication = value;

                this.SqlServerAuthentication = new SqlServerAuthentication(_authentication);

                OnPropertyChanged("SqlServerAuthentication");
                OnPropertyChanged("IntegratedSecurity");
            }
        }

        public CollectionView SqlServerAuthetications
        {
            get { return _sqlServerAuthentications; }
        }

        public string UserID
        {
            get
            {
                if (SqlServerAuthentication != null)
                    return SqlServerAuthentication.UserID;
                else
                    return "";
            }
            set
            {
                if (value != SqlServerAuthentication.UserID)
                {
                    SqlServerAuthentication.UserID = value;
                    OnPropertyChanged("UserID");
                }
            }
        }

        public string Password
        {
            get
            {
                if (SqlServerAuthentication != null)
                    return SqlServerAuthentication.Password;
                else
                    return "";
            }
            set
            {
                if (value != SqlServerAuthentication.Password)
                {
                    SqlServerAuthentication.Password = value;
                    OnPropertyChanged("Password");
                }
            }
        }


        #endregion

        #region Network protocol
        private IList<NetworkProtocol> networkProtocolList;
        private readonly CollectionView _networkProtocols;
        private NetworkProtocol NetworkProtocol;
        private string _networkProtocolName;
        public string NetworkProtocolName
        {
            get { return _networkProtocolName; }
            set
            {
                if (_networkProtocolName == value) return;
                _networkProtocolName = value;

                this.NetworkProtocol = new NetworkProtocol(_networkProtocolName);

                OnPropertyChanged("NetworkProtocol");
            }
        }

        public CollectionView NetworkProtocols
        {
            get { return _networkProtocols; }
        }



        #endregion

        #region Use Custom Color
        private bool _useCustomColor;
        public bool UseCustomColor
        {
            get { return _useCustomColor; }
            set
            {
                if (_useCustomColor = value) return;

                _useCustomColor = value;

                OnPropertyChanged("UseCustomColor");
            }
        }

        #endregion
        public ICommand ExitCommand
        {
            get
            {
                if (exitCommand == null)
                {
                    exitCommand = new DelegateCommand(Exit);
                }
                return exitCommand;
            }
        }

        private void Exit()
        {
            //Application.Current.Shutdown();
            Application.Current.Windows[0].Close();
        }

        public ConnectionPropertiesViewModel()
        {
            sqlServerInstanceList = new List<SqlServerInstance>();
            sqlServerAuthenticationList = new List<SqlServerAuthentication>();
            networkProtocolList = new List<NetworkProtocol>();

            checkForSqlServerInstances();
            bindSqlServerAuthetication();
            bindNetworkProtocols();

            _sqlServerInstances = new CollectionView(sqlServerInstanceList);
            _sqlServerAuthentications = new CollectionView(sqlServerAuthenticationList);
            _networkProtocols = new CollectionView(networkProtocolList);


        }

        private void bindSqlServerAuthetication()
        {
            foreach (Authentication auth in Enum.GetValues(typeof(Authentication)))
            {
                sqlServerAuthenticationList.Add(new SqlServerAuthentication(auth));
            }
        }

        private void bindNetworkProtocols()
        {
            foreach (Protocol auth in Enum.GetValues(typeof(Protocol)))
            {
                networkProtocolList.Add(new NetworkProtocol(auth));
            }
        }


        private void checkForSqlServerInstances()
        {
            RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
            using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
            {
                RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                if (instanceKey != null)
                {
                    foreach (var instanceName in instanceKey.GetValueNames())
                    {
                        sqlServerInstanceList.Add(new SqlServerInstance(Environment.MachineName, instanceName));
                    }
                }
            }
        }
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;


        #region Commands
        public ICommand ConnectClickCommand
        {
            get { return new DelegateCommand<object>(ConnectClick, CanClickConnect); }
        }

        private void ConnectClick(object context)
        {
            //MessageBox.Show("Instance: " + SqlServerInstanceCompleteName + " - Auth: " + SqlServerAuthentication.ToString());
            MainScreenViewModel mainScreenVM = new MainScreenViewModel(SqlServerInstance, SqlServerAuthentication);
            Views.MainScreen mainScreen = new Views.MainScreen();

            mainScreen.DataContext = mainScreenVM;
            mainScreen.Show();
            this.Exit();
        }

        private bool CanClickConnect(object context)
        {
            if (SqlServerInstanceCompleteName != null && SqlServerAuthentication != null)
                return true;
            else
                return false;
        }

        // OPTIONS Command - Opens Connection Properties Window
        public ICommand OptionsClickCommand
        {
            get { return new DelegateCommand<object>(OptionsClick, CanClickOptions); }
        }

        private void OptionsClick(object context)
        {
            Views.Login login = new Views.Login();
            login.Show();

            this.Exit();
        }

        private bool CanClickOptions(object context)
        {
            return true;
        }

        // Select Command - Opens Colour Window
        public ICommand SelectClickCommand
        {
            get { return new DelegateCommand<object>(SelectClick, CanClickSelect); }
        }

        private void SelectClick(object context)
        {
            //Views.ConnectionProperties connectionProperties = new Views.ConnectionProperties();

            //// connectionProperties.DataContext = mainScreenVM;
            //connectionProperties.Show();
            //this.Exit();
        }

        private bool CanClickSelect(object context)
        {
            return UseCustomColor;
        }


        #endregion
    }
}
